"use strict"
const App = getApp()
import {
    setStore,
    getStore
} from '../../utils/storage'
import {
    getWecddddshatUserPhone,
    login
} from '../../api/user/user'
import mode from '../../utils/mode'

Page({
    onShareAppMessage (options) {   //分享好友
        
        this.setData({
            isShare:1,
          })
        return {
            title: this.data.shareText||'2AM官方小程序',
            path: `/pages/shareIndex/shareIndex?share_id=${this.data.userMessage.id}&userName=${this.data.userMessage.user_nickname}`,
            imageUrl: 'https://2am-project.cn/img/20220325/shareImg.png',   //分享图片
        }
    },
    setInfo(){// 订阅消息
        let that = this
        this.setData({
          showShare:false,
          isShare:0
        })
        let shareData={
          user_id:that.data.userMessage.id,
          type:3,
          other_type:'',
        }
        wx.requestSubscribeMessage({
            tmplIds: that.data.temIds,
            success (res) {
              let arr = []
                if(res[that.data.temIds[0]]=='accept'){//拒绝
                  arr.push('1')
                }
                if(res[that.data.temIds[1]]=='accept'){
                  arr.push('2')
                }
                // else if(res[that.data.temIds[2]]=='accept'){
                  // arr.push('3')
                // }else if(res[that.data.temIds[3]]=='accept'){  //允许
                  // arr.push('4')
                // }
                if(arr.length>0){
                  shareData.other_type = arr.join(',')
                  that.sendSetYue(shareData)
                }
            },
            fail(error){
              console.log(error,'123失败');
            }
          })
      },
      sendSetYue(data){
        wx.$api.sendTemplate(data).then(res=>{
                if(res.code>0){
                }else{
                    wx.showToast({
                      title: res.msg,
                      icon:'none'
                    })
                }
        })
    },

    data: {
        night:false,
        temIds:['Wzq0Q8OpleP_KgHNxStTKJ6-8NdvRvqgJnioZ01w7bg','IKdsAyES45qURTGEQMaHqLRq-fpoaU83kNRtz3TcC78'],
        isShare:0,  //是否进行分享
        showShare:false,  //分享成功展示
        shareText:'邀你在线肌肤问诊，点...',
        logoStyle: 'width: 221px; height: 74px',

        share_id: '',
        shareOptions: [
            //   { name: '朋友圈', icon: 'wechat-moments', openType: 'share' },
            { name: '微信', icon: 'wechat', openType: 'share' },
            // { name: '复制链接', icon: 'link' },
            // { name: '分享海报', icon: 'poster' },
            // { name: '二维码', icon: 'qrcode' },
        ],

        whiteday: '../../image/logo@2x.png',
        logo: App.globalData.logo,
        score_info: '',
        type: '敏感',
        desc: '皮肤干燥，缺水',
        user: {},
        userMessage: null,
        matchGood: null,
        matchGoodType:1,
        night: false,
        num_num: '0',
        expiredCount: '0',
        is_over_test: 0,
        wxUserData: getStore('wxUserData'),
        integralCardColumn: [{
            icon: '../../image/icon/user/quanyi.png',
            title: '我的权益',
            url: '/pages/interests/interests'
        },
        {
            icon: '../../image/icon/user/jifen.png',
            title: '积分商城',
            url: '/pages/integral-goods/integral-goods'
        },
        {
            icon: '../../image/icon/user/vip.png',
            title: '专属顾问',
            url: '/pages/servers-card/servers-card'
        },
        {
            icon: '../../image/icon/user/zhuanqu.png',
            title: '赚取积分',
            url: '/pages/rule/rule'
        }
        ],
        inviteTsxColumn: [{
            num: '0',
            title: '成功邀约'
        },
        {
            num: '0000',
            title: '累计积分'
        },
        {
            num: '000',
            title: '即将获取积分'
        }
        ],
        orderCardColumn: [{
            // icon: '../../image/icon/payment@2x.png',
            icon: '../../image/icon/user/daifu.png',
            url: '/pages/order/order?type=1',
            title: '待付款',
            num: 0
        },
        {
            // icon: '../../image/icon/deliver@2x.png',
            icon: '../../image/icon/user/daifa.png',
            url: '/pages/order/order?type=2',
            title: '待发货',
            num: 0
        },
        {
            // icon: '../../image/icon/receiving@2x.png',
            icon: '../../image/icon/user/daishou.png',
            url: '/pages/order/order?type=3',
            title: '待收货',
            num: 0
        },
        {
            // icon: '../../image/icon/refund@2x.png',
            icon: '../../image/icon/user/tui.png',
            url: '/pages/afterSale/afterSale',
            title: '退款/售后',
            num: 0
        }
        ],
        serversNavigtoin: [
        // {
        //     url: '/pages/booking-tab/booking-tab',
        //     title: '我的预约'
        // },
        {
            url: '/pages/coupons/coupons',
            title: '我的优惠券'
        },
        {
            url: '/pages/testlist/testReport',
            title: '我的肌肤报告'
        },
        {
            url: '/pages/address/address',
            title: '我的地址'
        },
        {
            url: '/pages/exchange/exchange',
            title: '退换货政策'
        },
        {
            url: '/pages/servers-card/servers-card',
            title: '联系客服'
        },
        // {
        //     url: '/pages/store/store',
        //     title: '门店查询'
        // },
        {
            url: '/pages/question/question',
            title: '常见问题'
        },
        {
            url: '/pages/cooperation/cooperation',
            title: '企业合作'
        },
        {
            url: '/pages/join/join',
            title: '加入我们'
        }
        ],
        pageFlag: false,
        couponNum: {}
    },
    goUrl (e) {
        App.goUrl(e.target.dataset.item.url)
    },
    handleClickOpenLogiaDialog () {
        var that = this
        wx.navigateTo({
            url: '/pages/register/register',
        })
    },
    onLoad (options) {
        this.transition(0)
    },
    onShow () {
        
        this.setTabbar()

        var uinfo = wx.getStorageSync('uinfo') || null
        if (!uinfo || !uinfo.user) {
            wx.navigateTo({
                url: '/pages/register/register',
            })
            return
        }
        // if(this.data.isShare>0){
        //     this.setData({
        //       showShare:true
        //     })
        // }
        if(uinfo.user.is_enterprise==0){
            this.getAsk(uinfo.user.id)
        }
        
        let n = uinfo.user.user_nickname || ''
        let title =  n + '邀你在线肌肤问诊，点...'
        this.setData({
            shareText: title,
        })
        this.init()
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                selected: 3
            })
        }
    },
    
  setTabbar(){
    let night = this.hasNight(new Date().getHours())
    this.setData({
      night: night,
    })
    if (night) {
      wx.setTabBarStyle({
        color: '#AAA',
        selectedColor: '#fff',
        backgroundColor: '#000',
        borderStyle: "black",
      })
      wx.setTabBarItem({
        index: 0,
        selectedIconPath: "/image/navbar/1-1.png",
      }
      )
      wx.setTabBarItem({
        index: 1,
        selectedIconPath: "/image/navbar/2-1.png",
      })
      wx.setTabBarItem({
        index: 2,
        selectedIconPath: "/image/navbar/3-1.png",
      })
      wx.setTabBarItem({
        index: 3,
        selectedIconPath: "/image/navbar/4-1.png",
      })
    } else {
      wx.setTabBarStyle({
        color: '#AAA',
        selectedColor: '#000',
        backgroundColor: '#fff',
        borderStyle: "white",
      })
      wx.setTabBarItem({
        index: 0,
        selectedIconPath: "/image/navbar/1-3.png"
      }
      )
      wx.setTabBarItem({
        index: 1,
        selectedIconPath: "/image/navbar/2-3.png"
      })
      wx.setTabBarItem({
        index: 2,
        selectedIconPath: "/image/navbar/3-3.png"
      })
      wx.setTabBarItem({
        index: 3,
        selectedIconPath: "/image/navbar/4-3.png"
      })
    }
  },
    hasNight: function (hour) {
        return hour > 18 || hour < 7
    },
    getAsk(id){  //查询是否绑定微信
        let that = this
        wx.$api.getUserEnterprise({
                user_id:id
            }).then(res=>{
                if(res.code>0){
                    if(res.data>0){
                        that.getUserInfo(id)
                    }
                }else{
                    wx.showToast({
                      title: res.msg,
                      icon:'none'
                    })
                }
        })
    },
    async init () {
        // wx.showLoading({ mask: true })
        // this.setData({ pageFlag: false })
        var uinfo = wx.getStorageSync('uinfo')
        wx.setStorage({
            key: 'uinfo',
            data: uinfo
        })
        if (uinfo && uinfo.user) {
            this.setData({
                id: uinfo.user.id,
                is_over_test: uinfo.user.is_over_test
            })
            await this.getUserInfo(uinfo.user.id)
            await this.getMyShareScore(uinfo.user.id)
        } else {
            await this.getMathGood()
        }
        await this.getCouponNum()
        // 3-25 新增获取订单数量
        await this.getOrderNum()
        // wx.hideLoading()
        setTimeout(() => {
            this.setData({ pageFlag: true })
        }, 0)
    },
    transition (deltaY) {
        const offset = Math.min(Math.max(Math.abs(deltaY), 96), 220)
        this.setData({
            logoStyle: `width: ${offset}px; height: ${offset / 3}px;`
        })
    },
    getPhoneNumber (e) {
        // console.log('phone', e)
        const {
            sessionKey
        } = this.data.wxUserData
        const {
            id
        } = this.data.user
        const {
            encryptedData,
            iv
        } = e.detail
        const data = {
            iv,
            encryptedData,
            sessionKey,
            user_id: id
        }
        getWechatUserPhone(data).then(res => {
            console.log(res)
        })
    },
    getMyShareScore (id) {//获取我的分享积分
        var that = this
        wx.$api.shareIntegral({
                user_id: id,
            }).then(res=>{
                let resData = res.data
                // that.data.inviteTsxColumn[0].num = resData.count || 0
                // that.data.inviteTsxColumn[1].num = resData.integral || 0
                // that.data.inviteTsxColumn[2].num = resData.shareIntegral || 0
                that.setData({
                    inviteTsxColumn: that.data.inviteTsxColumn,
                    invitation: resData
                })
        })
    },
    toRegister () {
        if (this.data.userMessage) {
            wx.navigateTo({
                url: '../info/info',
            })
        } else {
            wx.navigateTo({
                url: '../register/register',
            })
        }

    },
    getCouponNum () {
        var that = this
        wx.$api.getCouponNum({
                userid: that.data.id
            }).then(res=>{
                that.setData({
                    num_num: res.data.count,
                    expiredCount: res.data.expiredCount,
                })
        })
    },
    toIntegral: function () {
        wx.navigateTo({
            url: '../integral-goods/integral-goods',
        })
    },
    toBanner () {
        // if(this.data.userMessage&&this.data.userMessage.subscribe==1){
        //     wx.showToast({
        //       title: '您已关注过公众号',
        //       icon:'none'
        //     })
        // }else 
        if (!this.data.userMessage) {
            wx.navigateTo({
                url: '/pages/register/register',
            })
        } else {
            wx.navigateTo({
                url: '../gongzhonghao/gongzhonghao',
            })
        }

    },
    toMyScore () {
        wx.navigateTo({
            url: '../record/record',
        })
    },
    getUserInfo (userid) {
        let that = this
        var uinfo = wx.getStorageSync('uinfo')
        mode.getUserInfo(userid).then(item => {
            item.data.level = uinfo.user.grade == 1 ? '银钻会员' : uinfo.user.grade == 2 ? '金钻会员' : uinfo.user.grade == 3 ? '黑钻会员' : ''
            uinfo.user = item.data
            wx.setStorage({ key: 'uinfo', data: uinfo })
            that.setData({
                userMessage: item.data
            })
            that.setData({
                score_info: item.data.score
            })
            that.getMathGood(item.data.score)
        })
    },
    getMathGood (score) {
        let that = this
        score = score ? score : 0
        mode.getIntegralMatch(score).then(item => {
            that.setData({
                matchGood: item.data.info,
                matchGoodType:item.data.type
            })
        })
    },
    lookReport () {
        let { userMessage, id } = this.data
        if (!userMessage || userMessage.is_member != 1) {
            wx.setStorage({
                data: '/pages/questionnaire/questionnaire',
                key: 'lastUrl',
            })
            wx.navigateTo({
                url: '../register/register',
            })
            return
        }
        if (!userMessage.is_over_test) {
            wx.navigateTo({
                url: '../questionnaire/questionnaire'
            })
            return
        }
        mode.getReportList(id).then(
            item => {
                // console.log('list', item.data)
                if (item && item.data.length > 0) {
                    let e = item.data[0]
                    wx.navigateTo({
                        url: '/pages/testReport/testRrport?id=' + e.id + '&answer=' + e.answer,
                    })
                }
            }
        )
    },
    goTest () {//去测试
        if (this.data.userMessage && this.data.userMessage.is_member == 1) {
            wx.navigateTo({
                url: '/pages/questionnaire/questionnaire',
            })
        } else {
            wx.setStorage({
                data: '/pages/questionnaire/questionnaire',
                key: 'lastUrl',
            })
            wx.navigateTo({
                url: '/pages/register/register',
            })
        }
    },
    goYHQ () {
        // this.data.userMessage.is_newUser==1&&
        if(this.data.num_num<1){
            wx.navigateTo({
                url: '/pages/servers-card/servers-card?isCoupon=1',
            })
        }else{
            wx.navigateTo({
                url: '/pages/coupons/coupons',
            })
        }
       
    },
    goMyShare (e) {
        // let item = e.currentTarget.dataset.index
        wx.navigateTo({
            url: '/pages/shareRecord/shareRecord',
        })
    },
    handleClickShare () {
        if (this.data.userMessage && this.data.userMessage.id) {
            wx.navigateTo({
                url: '/pages/sharePage/sharePage',
            })
        } else {
            wx.navigateTo({
                url: '../register/register',
            })
        }

    },
    memberGo (e) {
        if (!this.data.userMessage) {
            wx.navigateTo({
                url: '../register/register',
            })
            return
        }
        wx.navigateTo({ url: e.currentTarget.dataset.url })
    },
    goAllOrder () {
        wx.navigateTo({ url: '/pages/order/order' })
    },
    async getOrderNum () {
        let { code, data } = await wx.$api.getOrderNum({
            user_id: this.data.id
        })
        if (code) {
            this.data.orderCardColumn[0].num = data.wait_payment || 0
            this.data.orderCardColumn[1].num = data.wait_deliver_goods || 0
            this.data.orderCardColumn[2].num = data.wait_receiving || 0
            this.data.orderCardColumn[3].num = data.wait_after_sale || 0
            this.setData({
                orderCardColumn: this.data.orderCardColumn,
            })
        }
    },
    goZhuan () {
        let { userMessage } = this.data
        if (!userMessage || !userMessage.is_member) {
            wx.navigateTo({
                url: '../register/register',
            })
            return
        }
        if (userMessage.score) {
            wx.navigateTo({
                url: '../integral-goods/integral-goods',
            })
        } else {
            wx.navigateTo({ url: '/pages/rule/rule' })
        }
    },
    /**
    * 监听 TabBar 切换点击
    */
    onTabItemTap: function (item) {
        // console.log(item)
    }
})